import { userGetUserInfoApi, userLoginApi } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(), // 从本地存储获取 token
  userInfo: {},
  routes: constantRoutes
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 将 token 进行本地存储
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    // 将 token 从本地存储中移除
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 动态设置路由信息
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}
const actions = {
  async login(context, data) {
    const token = await userLoginApi(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await userGetUserInfoApi()
    context.commit('setUserInfo', res)
    return res
  },
  logout(context, message) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    resetRouter() // 重置路由配置
    Message({
      type: message.type,
      message: message.message
    })
    router.replace('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
